package com.sxbang.bms.config.jwt;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lmm
 * @date 2019/4/12 0012  15:48.
 */
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //自动排除生成token的路径,并且如果是options请求是cors跨域预请求，设置allow对应头信息
        if(request.getRequestURI().contains("swagger-")||request.getRequestURI().equals("/api/getPage")|| RequestMethod.OPTIONS.toString().equals(request.getMethod())){
            return true ;
        }
        String token = "";
        if(!StringUtils.isEmpty(request.getParameter("token"))){
            token = request.getParameter("token");
        }else{
            token = request.getHeader("token");
        }
        if (token == null || token.trim()=="") {
            throw new ServletException("无法获取token.");
        }
        try {
            JwtUtils.checkToken(token);
            return true;
        } catch (Exception e) {
            throw new ServletException(e.getMessage());
        }
    }
}
